package com.alinesno.cloud.operation.cmdb.controller.manager;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.operation.cmdb.advice.ConvertCode;
import com.alinesno.cloud.operation.cmdb.common.constants.HasStatusEnum;
import com.alinesno.cloud.operation.cmdb.common.excel.PoiExcelExport;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.DatabaseEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrderInfoEntity;
import com.alinesno.cloud.operation.cmdb.repository.DatabaseRepository;
import com.alinesno.cloud.operation.cmdb.web.bean.FileMeta;
import com.alinesno.cloud.operation.cmdb.web.bean.JqDatatablesPageBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;

/**
 * 后台主面板
 * 
 * @author LuoAnDong
 * @since 2018年8月14日 下午12:58:05
 */
@Controller
@RequestMapping("/manager/")
public class ManagerDatabaseController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private DatabaseRepository databaseRepository; // 订单详情服务
	
	/**
	 * 订单列表
	 * 
	 * @param model
	 * @param serverId
	 * @return
	 */
	@GetMapping("/database_list")
	public String list(Model model) {
		createMenus(model);
		return WX_MANAGER + "database_list";
	}
	
	@GetMapping("/database_import_data")
	public String importData(Model model) {
		return WX_MANAGER + "database_import_data";
	}
	
    @RequestMapping(value="/database_upload_data", method = RequestMethod.POST)
    public @ResponseBody LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    	
    	LinkedList<FileMeta> files =  qiniuUploadTool.uploadLocal(request , stackFileExport);
    	FileMeta f = files.get(0) ; 
    	String filePath = f.getFilePath() ;
    	
    	logger.debug("文件保存路径:{} , 保存路径:{}" , filePath , stackFileExport);
    
    	ImportParams params = new ImportParams();
        List<DatabaseEntity> result = ExcelImportUtil.importExcel(new File(filePath),DatabaseEntity.class, params);
        
        for (DatabaseEntity e : result) {
            logger.debug(ReflectionToStringBuilder.toString(e));
            e.setMasterCode(currentManager().getMasterCode());
            
            if(StringUtils.isNotBlank(e.getDbaLoginName())) {
            	databaseRepository.save(e) ; 
            }
        }
        
    	return files ; 
    }

	/**
	 * 订单列表
	 * 
	 * @param model
	 * @param serverId
	 * @return
	 */
	@GetMapping("/database_apply")
	public String apply(Model model) {
		return WX_MANAGER + "database_apply";
	}

	/**
	 * 数据库状态
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@PostMapping("/database_status")
	public ResponseBean<String> databaseStatus(Model model, String id, int status) {

		DatabaseEntity bean = databaseRepository.findById(id).get();
		bean.setHasStatus(status % 2);
		boolean b = databaseRepository.save(bean) != null;

		return b ? ResultGenerator.genSuccessMessage("保存成功.") : ResultGenerator.genFailMessage("保存失败.");
	}

	/**
	 * 数据库修改页面
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@GetMapping("/database_modify/{id}")
	public String goodsModify(Model model, @PathVariable("id") String id) {
		logger.debug("id = {}", id);

		DatabaseEntity bean = databaseRepository.findById(id).get();
		model.addAttribute("bean", bean);

		return WX_MANAGER + "database_modify";
	}

	/**
	 * 订单删除
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@GetMapping("/database_delete")
	public ResponseBean<String> orderDelete(Model model, String id) {
		databaseRepository.deleteById(id);
		return ResultGenerator.genFailMessage("删除成功.");
	}

	/**
	 * 数据列表
	 * 
	 * @return
	 */
	@ConvertCode
	@SuppressWarnings("unchecked")
	@ResponseBody
	@GetMapping("/database_list_data")
	public Object orderListData(Model model, JqDatatablesPageBean page) {
		JqDatatablesPageBean listPage = this.toPage(model, 
				page.buildFilter(OrderInfoEntity.class, request), 
				databaseRepository, 
				page);
		return listPage;
	}
	
	/**
	 * 数据导出
	 * @param model
	 * @param page
	 * @return
	 */
	@ResponseBody
	@PostMapping("/database_export")
	public ResponseBean<String> databaseExport(Model model, JqDatatablesPageBean page) {
		
		List<DatabaseEntity> listPage = this.toExport(model, page.buildFilter(OrderInfoEntity.class, request), databaseRepository, page , null);
		boolean b = false; 
		String saveName = null ; 
		
		if(listPage != null && listPage.size()>0) {
			
			saveName = UUID.randomUUID().toString()+".xls" ;  
			PoiExcelExport pee = new PoiExcelExport(stackFileExport , saveName ,"详情");
			
			String column[] = {"dbaLoginName","dataSpaceName","dataSpaceSize","indexSpaceName","indexSpaceSize","spaceDesc","managerMan","hostname","hostIp","sendTime","endTime"};
			String title[] = {"登陆名称","数据库空间","数据库空间大小","索引空间","索引空间大小","数据库使用描述","管理员","主机名称","主机IP","开始使用时间","开始使用时间"} ; 
			int size2[] = {15,20,20,20,20,23,15,15,15,20,20};
			
			pee.wirteExcel(column, title , size2 , listPage);
			logger.debug("list page = {}" , listPage);
			b = true ; 
		}
		
		return b ? ResultGenerator.genSuccessMessage(saveName) : ResultGenerator.genFailMessage("保存失败.");
	}


	/**
	 * 主机申请保存
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/database_apply_save", method = RequestMethod.POST)
	public ResponseBean<String> saveAdd(Model model, DatabaseEntity bean, String resources,
			HttpServletRequest request) {

		logger.debug("apply bean = {}", JSONObject.toJSONString(bean));

		// 查看是否已经存在登陆名
		bean.setMasterCode(currentManager().getMasterCode());
		bean.setHasStatus(HasStatusEnum.FORBIDDEN.getCode());
		
		boolean b = databaseRepository.save(bean) != null;

		return b ? ResultGenerator.genSuccessMessage("保存成功.") : ResultGenerator.genFailMessage("保存失败.");
	}

	/**
	 * 主机申请保存
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/database_modify_save", method = RequestMethod.POST)
	public ResponseBean<String> saveModify(Model model, DatabaseEntity bean, String resources,
			HttpServletRequest request) {

		logger.debug("apply bean = {}", JSONObject.toJSONString(bean));

		// 查看是否已经存在登陆名
		DatabaseEntity oldBean = databaseRepository.findById(bean.getId()).get();
		oldBean.setDbaLoginName(bean.getDbaLoginName());
		oldBean.setSpaceDesc(bean.getSpaceDesc());
		oldBean.setHostIp(bean.getHostIp());
		
		oldBean.setDataSpaceName(bean.getDataSpaceName());
		oldBean.setDataSpaceSize(bean.getDataSpaceSize());
		
		oldBean.setIndexSpaceName(bean.getIndexSpaceName());
		oldBean.setIndexSpaceSize(bean.getIndexSpaceSize());
		
		oldBean.setManagerMan(bean.getManagerMan());
		oldBean.setSendTime(bean.getSendTime());
		oldBean.setEndTime(bean.getEndTime());
		 
		boolean b = databaseRepository.save(oldBean) != null;
		
		return b ? ResultGenerator.genSuccessMessage("保存成功.") : ResultGenerator.genFailMessage("保存失败.");
	}

	/**
	 * 主机申请通过
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/database_apply_pass", method = RequestMethod.POST)
	public ResponseBean<String> savePass(Model model, String id, HttpServletRequest request) {
		
		logger.debug("id = {}" , id);

		DatabaseEntity bean = databaseRepository.findById(id).get();
		bean.setHasStatus(HasStatusEnum.NORMARL.getCode());
		boolean b = databaseRepository.save(bean) != null;

		return b ? ResultGenerator.genSuccessMessage("保存成功.") : ResultGenerator.genFailMessage("保存失败.");
	}

}
